package com.ninth_group.utils;

import com.ninth_group.datasource.HiveDataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.*;
import java.util.function.Function;

/**
 * Hive工具类
 */
@Component
public class
HiveUtil {
    @Resource
    private HiveDataSource hiveDataSource;

    private static HikariDataSource dataSource;

    @PostConstruct
    public void init() {
        try {
            Class.forName(hiveDataSource.getDriverClassName());
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(hiveDataSource.getUrl());
            config.setUsername(hiveDataSource.getUsername());
            config.setPassword(hiveDataSource.getPassword());
            config.setMaximumPoolSize(10);  // CPU * 2 + 1
            config.setMinimumIdle(2);
            config.setConnectionTimeout(30000L);
            dataSource = new HikariDataSource(config);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    // 查询
    public <T> List<T> executeQuery(String sql,
                                           Function<ResultSet, T> rowMapper,
                                           Object... params) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            setParameters(ps, params);

            // 构建调试信息--打印SQL
            StringBuilder debugSql = new StringBuilder(sql);
            for (Object param : params) {
                int index = debugSql.indexOf("?");
                if (index != -1) {
                    String replacement = "'" + param.toString().replace("'", "''") + "'";
                    debugSql.replace(index, index + 1, replacement);
                }
            }
            System.out.println("Debug SQL: " + debugSql.toString());

            try (ResultSet rs = ps.executeQuery()) {
                List<T> resultList = new ArrayList<>();
                while (rs.next()) {
                    resultList.add(rowMapper.apply(rs));
                }
                return resultList;
            }
        } catch (SQLException e) {
            throw new RuntimeException("Hive query error", e);
        }
    }

    // 查询 Map 形式的结果集
    public List<Map<String, Object>> queryForMap(String sql, Object... params) {
        return executeQuery(sql, rs -> {
            try {
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                Map<String, Object> row = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName, value);
                }
                return row;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }, params);
    }


    // 查询单个对象
    public <T> T queryForObject(String sql, Function<ResultSet, T> rowMapper, Object... params) {
        List<T> result = executeQuery(sql, rowMapper, params);
        return result.isEmpty() ? null : result.getFirst();
    }

    // 查询列表
    public <T> List<T> queryForList(String sql, Function<ResultSet, T> rowMapper, Object... params) {
        return executeQuery(sql, rowMapper, params);
    }

    // 查询单个值（如 count, max 等）
    public Object queryForSingleValue(String sql, Object... params) {
        return queryForObject(sql, rs -> {
            try {
                return rs.getObject(1);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }, params);
    }

    // 查询单个整数
    public Integer queryForInt(String sql, Object... params) {
        Object obj = queryForSingleValue(sql, params);
        return obj == null ? null : ((Number) obj).intValue();
    }

    // 查询单个长整型
    public Long queryForLong(String sql, Object... params) {
        Object obj = queryForSingleValue(sql, params);
        return obj == null ? null : ((Number) obj).longValue();
    }

    // 查询单个字符串
    public String queryForString(String sql, Object... params) {
        Object obj = queryForSingleValue(sql, params);
        return obj == null ? null : obj.toString();
    }

    // 添加
    public void executeUpdate(String sql, Object... params) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            setParameters(ps, params);
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("Hive update error", e);
        }
    }

    private void setParameters(PreparedStatement ps, Object[] params) throws SQLException {
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                Object param = params[i];
                if (param instanceof String) {
                    ps.setString(i + 1, (String) param);
                } else if (param == null) {
                    ps.setNull(i + 1, Types.VARCHAR); // 假设大多数字符串字段
                } else {
                    ps.setObject(i + 1, param); // 对于非字符串类型保持原样
                }
            }
        }
    }

//    private void setParameters(PreparedStatement ps, Object[] params) throws SQLException {
//        if (params != null) {
//            for (int i = 0; i < params.length; i++) {
//                ps.setObject(i + 1, params[i]);
//            }
//        }
//    }

    /**
     * 获取表所有列
     * @param hiveUtil HiveUtil工具类对象
     * @param tableName 表名
     * @return 字符串形式的表字段
     * @throws SQLException 抛出异常
     */
    public String getTableColumns(HiveUtil hiveUtil, String tableName) throws SQLException {
        List<String> columns = new ArrayList<>();
        String describeSql = "DESCRIBE " + tableName;

        Connection connection = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            connection = hiveUtil.getConnection(); // 通过hiveUtil获取连接
            stmt = connection.createStatement();
            rs = stmt.executeQuery(describeSql);

            while (rs.next()) {
                // 获取第一个字段（即 col_name 列）
                String columnName = rs.getString(1);
                if (columnName != null && !columnName.trim().isEmpty()) {
                    columns.add(columnName);
                }
            }
        } finally {
            // 确保资源被正确关闭
            if (rs != null) try { rs.close(); } catch (SQLException ignored) {}
            if (stmt != null) try { stmt.close(); } catch (SQLException ignored) {}
            if (connection != null) try { connection.close(); } catch (SQLException ignored) {}
        }

        return listToString(columns);
    }

    /**
     * 列表转字符串
     * @param list 要转换为字符串的列表
     * @return 转换后的字符串
     */
    public String listToString(List<String> list) {
        StringBuilder sb = new StringBuilder();
        for (String str : list) {
            sb.append(str).append(",");
        }
        if (!sb.isEmpty()) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

}
